package com.sg.service.biz.framework.nb;

import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.biz.framework.req.*;
import com.sg.dto.biz.framework.res.*;
import com.wicket.okrcomponent.common.exception.BizException;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ： 手工接入方法
 * @version 1.0
 * @since 2022/5/28 15:32
 */
@Service
public class NbInterfaceMode {

    @Resource
    private DataSource dataSource;

    /**
     * code:clearFieldCache
     * name:M1执行清除底层框架服务公共字段内存(特殊方法）
     * desc:undefined
     * gen by moon at 10/23/2022, 8:45:32 PM
     **/
    @Trace(operationName = "M1执行清除底层框架服务公共字段内存(特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBottomPublicFieldClearMemoryRespDto implementBottomPublicFieldClearMemory(ImplementBottomPublicFieldClearMemoryReqDto reqDto) {
        // TODO ruizhe skai dong ; 10/23/2022, 8:45:32 PM
        return new ImplementBottomPublicFieldClearMemoryRespDto();
    }

    /**
     * code:addMemoryBusinessData
     * name:M1新增框架内存业务数据（特殊方法）
     * desc:undefined
     * gen by moon at 4/2/2024, 11:32:52 PM
     **/
    @Trace(operationName = "M1新增框架内存业务数据（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddFrameWorkMemoryBusinessDataRespDto addFrameWorkMemoryBusinessData(AddFrameWorkMemoryBusinessDataReqDto reqDto) {
        // TODO ruizhe skai dong ; 4/2/2024, 11:32:52 PM
        return new AddFrameWorkMemoryBusinessDataRespDto();
    }

    /**
     * code:queryMemoryBusinessDatas
     * name:M1查询框架内存业务数据列表(特殊方法）
     * desc:undefined
     * gen by moon at 4/2/2024, 11:33:49 PM
     **/
    @Trace(operationName = "M1查询框架内存业务数据列表(特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryFrameWorkMemoryBusinessDataListRespDto queryFrameWorkMemoryBusinessDataList(QueryFrameWorkMemoryBusinessDataListReqDto reqDto) {
        // TODO ruizhe skai dong ; 4/2/2024, 11:33:49 PM
        return new QueryFrameWorkMemoryBusinessDataListRespDto();
    }

    /**
     * code:publicFieldCache
     * name:M1执行空间配置推送内存（FRAMEWORK）
     * desc:undefined
     * gen by moon at 5/19/2024, 2:20:16 PM
     **/
    @Trace(operationName = "M1执行空间配置推送内存（FRAMEWORK）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementSpaceConfPushMemoryFrameworkRespDto implementSpaceConfPushMemoryFramework(ImplementSpaceConfPushMemoryFrameworkReqDto reqDto) {
        ImplementSpaceConfPushMemoryFrameworkRespDto retData = new ImplementSpaceConfPushMemoryFrameworkRespDto();
        Map<String, Object> confPool = CommonFunctionHelper.getBizConfigInfo();
        if (confPool.containsKey(reqDto.getSpaceId())) {
            Map<String, Object> spaceConfig = (Map<String, Object>) confPool.get(reqDto.getSpaceId());
            spaceConfig.put("fileDisplayRootPath", reqDto.getFileDisplayRootPath());
        } else {
            Map<String, Object> spaceConfig = new HashMap<>();
            spaceConfig.put("fileDisplayRootPath", reqDto.getFileDisplayRootPath());
            confPool.put(reqDto.getSpaceId(), spaceConfig);
        }
        return retData;
    }


    @Trace(operationName = "组装sql")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public String buildSql(ImplementGeneralSegBaseDataReqDto reqDto) {

        Map<String, String> queryKey = new HashMap<>();

        Map<String, String> timeQueryRuleKey = new HashMap<>();
        if (reqDto.getRefCustomField1() != null && reqDto.getRefCustomFieldValue1() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField1()), reqDto.getRefCustomFieldValue1());
        }

        if (reqDto.getRefCustomField2() != null && reqDto.getRefCustomFieldValue2() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField2()), reqDto.getRefCustomFieldValue2());
        }

        if (reqDto.getRefCustomField3() != null && reqDto.getRefCustomFieldValue3() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField3()), reqDto.getRefCustomFieldValue3());
        }

        if (reqDto.getRefCustomField4() != null && reqDto.getRefCustomFieldValue4() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField4()), reqDto.getRefCustomFieldValue4());
        }

        if (reqDto.getRefCustomField5() != null && reqDto.getRefCustomFieldValue5() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField5()), reqDto.getRefCustomFieldValue5());
        }

        if (reqDto.getRefCustomField6() != null && reqDto.getRefCustomFieldValue6() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField6()), reqDto.getRefCustomFieldValue6());
        }

        if (reqDto.getRefCustomField7() != null && reqDto.getRefCustomFieldValue7() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField7()), reqDto.getRefCustomFieldValue7());
        }

        if (reqDto.getRefCustomField8() != null && reqDto.getRefCustomFieldValue8() != null) {
            queryKey.put(CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField8()), reqDto.getRefCustomFieldValue8());
        }


        StringBuilder where = new StringBuilder();
        if (!queryKey.isEmpty()) {
            where.append(" WHERE ");
            for (Map.Entry<String, String> entry : queryKey.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                where.append(key).append(" = ").append("'").append(value).append("'").append(" AND ");
            }


            if (reqDto.getBusinessDataSetPrimaryKeyName() != null
                    && !reqDto.getBusinessDataSetPrimaryKeyName().isEmpty()
                    && reqDto.getLastDataObjectId() != null
                    && !reqDto.getLastDataObjectId().isEmpty()) {
                where.append(CommonFunctionHelper.humpToUnderline(reqDto.getBusinessDataSetPrimaryKeyName())).append(" > ").append("'").append(reqDto.getLastDataObjectId()).append("'").append(" AND ");
            }
            where.delete(where.length() - 5, where.length());
        }

        StringBuilder orderBy = new StringBuilder();
        if (reqDto.getOrderFieldName() != null) {
            orderBy.append(" order by " + CommonFunctionHelper.humpToUnderline(reqDto.getOrderFieldName()));
        }

        if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_LARGE_TO_SMALL")) {
            orderBy.append(" desc ");
        } else if (reqDto.getOrderRule() != null && reqDto.getOrderRule().equals("FROM_SMALL_TO_LARGE")) {
            orderBy.append(" asc ");
        }

        StringBuilder limit = new StringBuilder();
        if (reqDto.getDatasNum() != null) {
            limit.append(" limit " + reqDto.getDatasNum());
        }


        String selectPreFixStr = "SELECT * FROM " + reqDto.getBusinessDataSetTableName() + " ";
        String sql = selectPreFixStr + where.toString() + orderBy.toString() + limit.toString();
        return sql;
    }

    /**
     * code:subsectionQueryBusinessDataSet
     * name:M1执行分段查询框架服务数据对象
     * desc:undefined
     * gen by moon at 5/31/2024, 2:25:49 AM
     **/
    @Trace(operationName = "M1执行分段查询框架服务数据对象")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementGeneralSegBaseDataRespDto implementGeneralSegBaseData(ImplementGeneralSegBaseDataReqDto reqDto) {
        ImplementGeneralSegBaseDataRespDto retData = new ImplementGeneralSegBaseDataRespDto();
        String sql = buildSql(reqDto);
        try (Connection connection = dataSource.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {

            Map<String, Field> fieldIndex = new HashMap<>();
            Field[] fields = BaseDataDto.class.getDeclaredFields();
            for (Field one : fields) {
                one.setAccessible(true);
                fieldIndex.put(one.getName(), one);
            }

            while (resultSet.next()) {
                BaseDataDto elm = new BaseDataDto();
                for (OutputDataDto oneField : reqDto.getOutputDataList()) {
                    Object value = resultSet.getObject(CommonFunctionHelper.humpToUnderline(oneField.getFieldName()));
                    Field field = fieldIndex.get(oneField.getMapFieldName());
                    if (value != null) {
                        try {
                            field.set(elm, String.valueOf(value));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
                retData.getBaseDataList().add(elm);
            }
        } catch (Exception e) {
            throw new BizException("M3执行通用分段查询业务数据对象-寻找数据异常:(" + e + ")", false);
        }
        return retData;
    }
    //手工接入方法
}
